import express from "express";
import upload from "../middleware/upload.js";
import authMiddleware from "../middleware/auth.js";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const router = express.Router();

// 确保上传目录存在
const uploadDir = path.join(__dirname, "../uploads/id-cards");
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// 上传身份证照片
router.post("/id-card", authMiddleware, upload.single("file"), (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: "请选择要上传的文件" });
    }

    const fileUrl = `/uploads/id-cards/${req.file.filename}`;

    res.json({
      message: "文件上传成功",
      url: fileUrl,
      filename: req.file.filename,
      originalName: req.file.originalname,
      size: req.file.size,
    });
  } catch (error) {
    console.error("文件上传错误:", error);
    res.status(500).json({ error: "文件上传失败" });
  }
});

// 删除文件
router.delete("/file/:filename", authMiddleware, (req, res) => {
  try {
    const { filename } = req.params;
    const filePath = path.join(__dirname, "../uploads/id-cards", filename);

    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath);
      res.json({ message: "文件删除成功" });
    } else {
      res.status(404).json({ error: "文件不存在" });
    }
  } catch (error) {
    console.error("文件删除错误:", error);
    res.status(500).json({ error: "文件删除失败" });
  }
});

export default router;
